<template>
  <div class="login-container">
    <!-- 背景装饰元素 -->
    <div class="login-bg-decoration"></div>

    <div class="login-card">
      <!-- 左侧插图区域 -->
      <div class="login-illustration">
        <div class="illustration-content">
          <h1 class="system-main-title">蜂农定位系统</h1>
          <p class="system-desc">精准定位 · 科学管理 · 高效养蜂</p>
          <img src="@/assets/images/dw2.svg" alt="蜂农定位插图" class="illustration-img" />
        </div>
      </div>

      <!-- 右侧登录表单 -->
      <el-form ref="loginRef" :model="loginForm" :rules="loginRules" class="login-form">
        <h2 class="login-title">账号登录</h2>

        <!-- 用户名输入 -->
        <el-form-item prop="username">
          <el-input v-model="loginForm.username" type="text" size="large" auto-complete="off" placeholder="请输入账号"
            class="form-input">
            <template #prefix><svg-icon icon-class="user" class="el-input__icon input-icon" /></template>
          </el-input>
        </el-form-item>

        <!-- 密码输入 -->
        <el-form-item prop="password">
          <el-input v-model="loginForm.password" type="password" size="large" auto-complete="off" placeholder="请输入密码"
            @keyup.enter="handleLogin" class="form-input">
            <template #prefix><svg-icon icon-class="password" class="el-input__icon input-icon" /></template>
          </el-input>
        </el-form-item>

        <!-- 验证码 -->
        <el-form-item prop="code" v-if="captchaEnabled">
          <el-input v-model="loginForm.code" size="large" auto-complete="off" placeholder="请输入验证码" style="width: 63%"
            @keyup.enter="handleLogin" class="form-input">
            <template #prefix><svg-icon icon-class="validCode" class="el-input__icon input-icon" /></template>
          </el-input>
          <div class="login-code">
            <img :src="codeUrl" @click="getCode" class="login-code-img" />
          </div>
        </el-form-item>

        <!-- 记住密码 -->
        <el-checkbox v-model="loginForm.rememberMe" class="remember-me">
          记住密码
        </el-checkbox>

        <!-- 登录按钮 -->
        <el-form-item class="login-btn-group">
          <el-button :loading="loading" size="large" type="primary" style="width:100%;" @click.prevent="handleLogin"
            class="login-btn">
            <span v-if="!loading">登 录</span>
            <span v-else>登 录 中...</span>
          </el-button>

          <!-- 辅助链接 -->
          <div class="link-group">
            <router-link class="link-type" :to="'/phoneLogin'" replace>
              手机号登录
            </router-link>
            <span class="link-separator">|</span>
            <router-link class="link-type" :to="'/forget'">忘记密码</router-link>
            <router-link class="link-type register-link" :to="'/register'" v-if="register">
              立即注册
            </router-link>
          </div>
        </el-form-item>
      </el-form>
    </div>

    <!-- 页脚 -->
    <div class="login-footer">
      <span>© 2025 蜂农管理系统 版权所有</span>
    </div>
  </div>
</template>

<script setup>
import { getCodeImg } from "@/api/login";
import Cookies from "js-cookie";
import { encrypt, decrypt } from "@/utils/jsencrypt";
import useUserStore from '@/store/modules/user'
import { ElMessage } from 'element-plus';
import { ref, watch, getCurrentInstance } from 'vue';
import { useRoute, useRouter } from 'vue-router';

const userStore = useUserStore()
const route = useRoute();
const router = useRouter();
const { proxy } = getCurrentInstance();

// 经纬度信息
const locationData = ref({
  longitude: null,
  latitude: null
});

const loginForm = ref({
  username: "admin",
  password: "admin123",
  rememberMe: false,
  code: "",
  uuid: "",
  longitude: null,
  latitude: null
});

// 百度地图定位
const getGeolocation = () => {
  return new Promise((resolve, reject) => {
    if (window.BMap) {
      startBaiduLocation(resolve, reject);
    } else {
      const AK = "KMaw3R2d9yQzAT44NI7aDAviwUpCPkoM";
      const script = document.createElement('script');
      script.src = `https://api.map.baidu.com/api?v=3.0&ak=${AK}&callback=initBMap`;
      script.type = 'text/javascript';
      script.onerror = () => reject(new Error('百度地图加载失败'));
      document.head.appendChild(script);
      window.initBMap = () => startBaiduLocation(resolve, reject);
    }
  });
};

const startBaiduLocation = (resolve, reject) => {
  const geolocation = new BMap.Geolocation();
  geolocation.getCurrentPosition(
    (position) => {
      if (!position || !position.point) {
        ElMessage.error('定位失败：未获取到有效坐标');
        resolve(false);
        return;
      }

      locationData.value.longitude = position.point.lng;
      locationData.value.latitude = position.point.lat;
      loginForm.value.longitude = locationData.value.longitude;
      loginForm.value.latitude = locationData.value.latitude;
      ElMessage.success('位置信息获取成功');
      resolve(true);
    },
    (error) => {
      let errorMsg = '位置信息获取失败：';
      switch (error.code) {
        case 1: errorMsg += '用户拒绝授权'; break;
        case 2: errorMsg += '位置信息不可用'; break;
        case 3: errorMsg += '获取超时'; break;
        default: errorMsg += error.message || '未知错误';
      }
      ElMessage.error(errorMsg);
      resolve(false);
    },
    { enableHighAccuracy: false, timeout: 30000, maximumAge: 30000 }
  );
};

const loginRules = {
  username: [{ required: true, trigger: "blur", message: "请输入您的账号" }],
  password: [{ required: true, trigger: "blur", message: "请输入您的密码" }],
  code: [{ required: true, trigger: "change", message: "请输入验证码" }]
};

const codeUrl = ref("");
const loading = ref(false);
const captchaEnabled = ref(true);
const register = ref(true);
const redirect = ref(undefined);

watch(route, (newRoute) => {
  redirect.value = newRoute.query && newRoute.query.redirect;
}, { immediate: true });

async function handleLogin() {
  proxy.$refs.loginRef.validate(async valid => {
    if (valid) {
      loading.value = true;
      if (loginForm.value.rememberMe) {
        Cookies.set("username", loginForm.value.username, { expires: 30 });
        Cookies.set("password", encrypt(loginForm.value.password), { expires: 30 });
        Cookies.set("rememberMe", loginForm.value.rememberMe, { expires: 30 });
      } else {
        Cookies.remove("username");
        Cookies.remove("password");
        Cookies.remove("rememberMe");
      }

      userStore.login(loginForm.value).then(() => {
        const query = route.query;
        const otherQueryParams = Object.keys(query).reduce((acc, cur) => {
          if (cur !== "redirect") {
            acc[cur] = query[cur];
          }
          return acc;
        }, {});
        router.push({ path: redirect.value || "/", query: otherQueryParams });
      }).catch(() => {
        loading.value = false;
        if (captchaEnabled.value) {
          getCode();
        }
      });
    }
  });
}

function getCode() {
  getCodeImg().then(res => {
    captchaEnabled.value = res.captchaEnabled === undefined ? true : res.captchaEnabled;
    if (captchaEnabled.value) {
      codeUrl.value = "data:image/gif;base64," + res.img;
      loginForm.value.uuid = res.uuid;
    }
  });
}

function getCookie() {
  const username = Cookies.get("username");
  const password = Cookies.get("password");
  const rememberMe = Cookies.get("rememberMe");
  loginForm.value = {
    username: username === undefined ? loginForm.value.username : username,
    password: password === undefined ? loginForm.value.password : decrypt(password),
    rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
  };
}

// 初始化
getCode();
getCookie();
getGeolocation();
</script>

<style lang='scss' scoped>
.login-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-image: url("../assets/images/login-background7.jpg");
  // background: #141313;
  background-size: cover;
  background-position: center;
  background-attachment: fixed;
  padding: 20px;
  box-sizing: border-box;
  position: relative;
  overflow: hidden;

  // 背景装饰
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    // background: rgba(255, 255, 255, );
    z-index: 1;
  }

  >* {
    position: relative;
    z-index: 2;
  }
}

// 背景装饰元素
.login-bg-decoration {
  position: absolute;
  top: -10%;
  right: -10%;
  width: 40%;
  height: 40%;
  background: rgba(47, 128, 237, 0.1);
  border-radius: 50%;
  z-index: 1;
  filter: blur(80px);
}

.login-card {
  display: flex;
  width: 100%;
  max-width: 1000px;
  margin: auto;
  // background: rgba(225, 225, 225, 0.9); 
  border-radius: 16px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  transition: all 0.3s ease;

  // 响应式调整
  @media (max-width: 768px) {
    flex-direction: column;
    width: 90%;
  }
}

// 左侧插图区域
.login-illustration {
  flex: 1;
  background: linear-gradient(135deg, rgb(167, 148, 148, 0.5) 0%, rgba(215, 237, 47, 0.6) 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px;
  color: #ffffff;

  .illustration-content {
    text-align: center;
    max-width: 300px;
  }

  .system-main-title {
    font-size: 32px;
    /* 字体大小增大，更醒目 */
    color: #ffffff;
    /* 白色字体，与左侧渐变背景对比更清晰 */
    margin-bottom: 15px;
    font-weight: 700;
    /* 字体加粗，增强视觉重量 */
    text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    /* 增加文字阴影，提升层次感 */
  }

  .system-desc {
    font-size: 18px;
    /* 字体大小增大，提升可读性 */
    color: rgba(255, 255, 255, 0.95);
    /* 白色带透明度，与背景对比更柔和清晰 */
    margin-bottom: 30px;
    line-height: 1.6;
    font-weight: 500;
    /* 增加字体重量，让文字更醒目 */
    text-shadow: 0 1px 3px rgba(0, 0, 0, 0.15);
    /* 文字阴影增强层次感，在渐变背景上更易读 */
  }

  .illustration-img {
    max-width: 100%;
    max-height: 250px;
    object-fit: contain;
    transition: transform 0.3s ease;

    &:hover {
      transform: scale(1.05);
    }
  }

  @media (max-width: 768px) {
    padding: 30px 20px;

    .system-main-title {
      font-size: 24px;
    }

    .system-desc {
      font-size: 14px;
    }
  }
}

// 登录表单样式
.login-form {
  flex: 1;
  padding: 50px 40px;
  display: flex;
  flex-direction: column;
  background: rgba(252, 252, 252, 0.6);

  @media (max-width: 768px) {
    padding: 30px 20px;
  }

  .login-title {
    font-size: 24px;
    color: #333;
    text-align: center;
    margin-bottom: 30px;
    font-weight: 600;
    position: relative;

    &::after {
      content: '';
      display: block;
      width: 40px;
      height: 3px;
      background: #2f80ed;
      margin: 10px auto 0;
      border-radius: 3px;
    }
  }

  .form-input {
    height: 50px;
    border-radius: 8px;
    border: 1px solid #e0e0e0;
    transition: all 0.3s ease;

    &:hover,
    &:focus-within {
      border-color: #2f80ed;
      box-shadow: 0 0 0 3px rgba(47, 128, 237, 0.1);
    }

    input {
      height: 50px;
      font-size: 15px;
    }
  }

  .input-icon {
    color: #888;
    transition: color 0.3s ease;
  }

  .form-input:focus-within .input-icon {
    color: #2f80ed;
  }

  .remember-me {
    font-size: 14px;
    color: #666;
    margin: 10px 0 25px;
    display: flex;
    align-items: center;

    .el-checkbox__label {
      padding-left: 8px;
    }
  }

  .login-btn-group {
    margin-top: 15px;
  }

  .login-btn {
    height: 50px;
    font-size: 16px;
    background: #2f80ed;
    border: none;
    border-radius: 8px;
    transition: all 0.3s ease;

    &:hover {
      background: #1e5cad;
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(47, 128, 237, 0.3);
    }

    &:active {
      transform: translateY(0);
    }
  }

  .link-group {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 20px;
    flex-wrap: wrap;
    gap: 10px;
  }

  .link-type {
    color: #141313;
    font-size: 14px;
    text-decoration: none;
    transition: all 0.2s ease;

    &:hover {
      color: #2f80ed;
      text-decoration: none;
    }
  }

  .register-link {
    color: #2f80ed;
    font-weight: 500;
  }

  .link-separator {
    color: #ddd;
    margin: 0 8px;
  }

  .login-code {
    width: 33%;
    height: 50px;
    display: flex;
    align-items: center;
    justify-content: flex-end;

    .login-code-img {
      height: 50px;
      border-radius: 8px;
      cursor: pointer;
      transition: transform 0.2s ease;

      &:hover {
        transform: scale(1.05);
      }
    }
  }
}

// 页脚样式
.login-footer {
  text-align: center;
  color: #0f9ee5;
  font-size: 13px;
  padding: 20px 0;
  margin-top: 30px;
}
</style>